import java.util.Arrays;

public class todaytest {
    class MyPriorityQueue {
        public int[] elem;
        public int usesize;

        public MyPriorityQueue() {
            this.elem = new int[10];
        }

        public void newarr(int[] arr) {
            for (int i = 0; i < arr.length; i++) {
                this.elem[i] = arr[i];
                usesize++;
            }
        }

        public void upper() {
            for (int panter = (usesize - 1) / 2; panter >= 0; panter--) {
                int childer = panter * 2 + 1;
                while (childer < usesize) {
                    if (childer + 1 < usesize && elem[childer] < elem[childer + 1]) {
                        childer++;
                    }
                    if (elem[panter] < elem[childer]) {
                        jiao(elem, panter, childer);
                        panter = childer;
                        childer = panter * 2 + 1;
                    } else {
                        break;
                    }
                }
            }
        }

        public void add(int val) {
            if (iffull()) {
                elem = Arrays.copyOf(elem, elem.length * 2);
            }
            elem[usesize] = val;
            usesize++;
            int childer = usesize - 1;
            uppoff(childer);
        }

        public void uppoff(int childer) {
            while (childer != 0) {
                int parter = (childer - 1) / 2;
                if (elem[parter] < elem[childer]) {
                    jiao(elem, parter, childer);
                    childer = parter;
                    parter = (childer - 1) / 2;
                }
            }
        }

        public boolean iffull() {
            return usesize == elem.length;
        }

        public void jiao(int[] elem, int ret1, int ret2) {
            int temp = elem[ret1];
            elem[ret1] = elem[ret2];
            elem[ret2] = temp;
        }

        @Override
        public String toString() {
            return "MyPriorityQueue{" +
                    "elem=" + Arrays.toString(elem) +
                    ", usesize=" + usesize +
                    '}';
        }

        public void main(String[] args) {
            int[] arr = {27, 15, 19, 18, 28, 34, 65, 49, 25, 37};
            MyPriorityQueue myPriorityQueue = new MyPriorityQueue();
            myPriorityQueue.newarr(arr);
            System.out.println(myPriorityQueue.toString());
            System.out.println("以大堆排序后:");
            myPriorityQueue.upper();
            System.out.println(myPriorityQueue.toString());
            System.out.println("添加新元素后面的大堆排序");
            myPriorityQueue.add(88);
            System.out.println(myPriorityQueue.toString());
        }
    }
}
